/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.report_definition_service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.hiddenequity.utils.XMLUtils;

public class ReportDefinitionResponseParser {

	Document _XMLDocument;

	
	/*
	 * Constructor
	 */
	public ReportDefinitionResponseParser(String XMLData){
		try {
			_XMLDocument = XMLUtils.XMLStringToDoc(XMLData);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}//Constructors
	
	
	
	/*
	 * Check response for errors
	 */
	public String checkForErrors(){
		String error = null;
		try {
	        
	        NodeList faultstring = _XMLDocument.getElementsByTagName("faultstring");
	        error =  XMLUtils.getCharacterDataFromElement((Element) faultstring.item(0));

	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return error;
	}//checkForErrors
	
	
	
	/*
	 * Read report columns
	 */
	public ArrayList<Map<String, String>> getReportColumns(){
		ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
		try {	
			NodeList nodes = _XMLDocument.getElementsByTagName("column");
	        for (int i = 0; i < nodes.getLength(); i++) {
	        	Map<String, String> temp = new HashMap<String, String>();
	        	Element element = (Element) nodes.item(i);
	    		String name = element.getAttribute("name");
	    		String display = element.getAttribute("display");
	    		temp.put(name, display);
	        	list.add(temp);
	        }
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return list;
	}//gerReportColumns
	
	
	
	/*
	 * Read report rows
	 */
	public ArrayList<Map<String, String>> getReportRows(ArrayList<Map<String, String>> columns){
		
		ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
		try {	
			NodeList nodes = _XMLDocument.getElementsByTagName("row");
	        for (int i = 0; i < nodes.getLength(); i++) {
	        	Map<String, String> reportRow = new HashMap<String, String>();
	        	Element element = (Element) nodes.item(i);

	        	for(Map<String, String> column : columns){
		            for(Map.Entry<String, String> entry : column.entrySet()) {
		            	reportRow.put(entry.getValue(), element.getAttribute(entry.getKey()));
		            }
	        	}
	        	list.add(reportRow);
	        }
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return list;	
		
	}//getReportRows
	
	
}
